import styles from './index.less';
import CInput from '../prefix-input';
import type { FC } from 'react';
import { useEffect, useState } from 'react';

interface Props {
  value?: number[];
  onChange?: (prices: number[]) => void;
}

const Index: FC<Props> = ({ onChange, value }) => {
  const [val, setVal] = useState<(number | undefined)[]>([undefined]); // {}
  const update = (prices) => {
    if (onChange) {
      onChange(prices);
    } else {
      setVal(prices);
    }
  };
  const _onChange = (index, evt) => {
    const newVal = [...val];
    newVal[index] = evt.target.value?.replace(/^(0+)|[^\d]+/g, '');
    update(newVal);
  };
  const onRemove = (index) => {
    const pre = val.slice(0, index);
    const suf = val.slice(index + 1);
    update([...pre, ...suf]);
  };
  useEffect(() => {
    setVal(!value || !value.length ? [undefined] : value);
  }, [value]);
  return (
    <div className={styles.container}>
      {val.map((price, index) => {
        return (
          <div key={`price-${index}`}>
            <span>
              拉<span>{index + 1}</span>个用户购买
            </span>
            <CInput
              containerClassName={styles.input}
              value={price}
              onChange={(evt) => _onChange(index, evt)}
              prefixText="返现学习币"
              placeholder="填写额度，不可超过课程售价"
            />
            <i className={styles.remove} onClick={() => onRemove(index)}>
              X
            </i>
          </div>
        );
      })}
    </div>
  );
};
export default Index;
